# -*- coding:utf-8 -*-
import Pluto,struct,codecs,os,fnmatch,re

#利用码表生成字典
def makedic():
        dic={}
        tbl=codecs.open('in.tbl','r+b','utf_16')
        for line in tbl:
                line_split=line.replace('\r\n','').split(u'=')
                dic[line_split[1]]=line_split[0].lower()
        tbl.close()
        return dic

mydic=makedic()

def makestr(i):
        string=[]
        j=0
        while j>=0:
                if re.match(u'－'*18,lines[i+2+j]):
                        break
                string.append(lines[i+2+j])
                j+=1
        return ''.join(string)[:-2]

#写入单字节
def bytewrite(j):
        return chr(int(mydic[string[j]],16))

#写入unicode字符
def wordwrite(j):
        return chr(int(mydic[string[j]][:2],16))+chr(int(mydic[string[j]][2:4],16))

fl=Pluto.walk('script')
for fn in fl:
        if not fnmatch.fnmatch(fn,'*.txt'):
                continue
        if '.bin' in fn:
                continue
        print fn
        fp=codecs.open(fn,'rb','utf16')
        lines=fp.readlines()
        fp.close()
        line_num=len(lines)
        
        text_list=[]
        for i in xrange(line_num):
                if re.match('No.\d+',lines[i]):
                        text=makestr(i)
                        text_list.append(text)
        num=len(text_list)
        tar=open(fn[:-4],'r+b')
        tar.seek(4)
        point=struct.unpack('i',tar.read(4))[0]
        baseoffset=point+8
        tar.seek(baseoffset)
        tar.write(struct.pack('i',num))
        tar.seek(baseoffset+4+num*8)
        offsetlist=[]
        sizelist=[]
        for string in text_list:
                startoffset=tar.tell()
                offsetlist.append(startoffset-4-baseoffset)
                j=0
                while j<len(string):

                        if string[j] in mydic:

                                if len(mydic[string[j]])==4:
                                        tar.write(wordwrite(j))

                                if len(mydic[string[j]])==2:
                                        tar.write(bytewrite(j))
                                j+=1
                        else:
                                print string[j],'not in tbl'
                                j+=1
                endoffset=tar.tell()
                sizelist.append(endoffset-startoffset)
        pointnum=len(offsetlist)
        for k in xrange(pointnum):
                tar.seek(baseoffset+4+k*8)
                tar.write(struct.pack('i',offsetlist[k]))
                tar.write(struct.pack('i',sizelist[k]))
        tar.close()
